﻿using jinmaMesProxy.DataAccess;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;

namespace jinmaMesProxy
{
    public static class Utils
    {
        public static string Serialize(object data)
        {
            return JsonConvert.SerializeObject(data);
        }
        public static T? Deserialize<T>(string str)
        {
            return JsonConvert.DeserializeObject<T>(str);
        }
        public static List<T> JArrayToList<T>(JArray jarray)
        {
            List<T> list = new List<T>();
            foreach (var item in jarray)
            {
                list.Add(item.ToObject<T>()!);
            }
            return list;
        }
        public static T Clone<T>(T data)
        {
            return Deserialize<T>(Serialize(data!))!;
        }

        public static void Restore<T>(T data, T backup)
        {
            foreach (var p in typeof(T).GetProperties())
            {
                p.SetValue(data, p.GetValue(backup));
            }
        }

        public static string Md5(string str)
        {
            string pwd = "";
            MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
            for (int i = 0; i < s.Length; i++)
            {
                pwd = pwd + s[i].ToString("X2");
            }
            return pwd.ToUpper();
        }

        public static string GetCharVer(int ver)
        {
            string charver;
            if (ver <= 10) charver = (ver - 1).ToString();
            else charver = Convert.ToChar(64 + (ver - 10)).ToString();
            return charver;
        }

        public static void SetVouchFromReader<T>(T data, PropertyInfo p, SqlDataReader reader)
        {
            var att = p.GetCustomAttribute<MyColumnNameAttribute>();
            if (att == null) return;
            var v = reader[att.ColumnName];
            var t = v.GetType();
            if (t == typeof(DBNull))
                p.SetValue(data, null);
            else if (t == typeof(DateTime))
                p.SetValue(data, ((DateTime)v).ToString("yyyy-MM-dd HH:mm:ss.fff"));
            else if (t == typeof(String))
                p.SetValue(data, v.ToString());
            else
                p.SetValue(data, v);
        }
    }
}
